import java.util.*;


public class VehicleQueue implements Observer {
	private double vehiclesPerSecondEnter;
	private int trafficLightRate;
	private double vehiclesPerSecondLeave;
	private boolean greenLight;
	
	private VehicleGenerator generator;
	private LinkedList<Vehicle> queue;
	
	
	public VehicleQueue(double vehiclesPerSecondEnter, int trafficLightRate, double vehiclesPerSecondLeave, VehicleGenerator generator) {
		this.vehiclesPerSecondEnter = vehiclesPerSecondEnter;
		this.trafficLightRate = trafficLightRate;
		this.vehiclesPerSecondLeave = vehiclesPerSecondLeave;
		this.generator = generator;
		greenLight = false;
		queue = new LinkedList<Vehicle>();
	}
	
	
	public void enter() {
		int enterQueue = (int) (1/vehiclesPerSecondEnter);
		if (Time.getInstance().getCurrentTime() % enterQueue == 0)
			queue.add(generator.createVehicle());
	}
	
	public void leave() {
		if (greenLight) {
			int leaveQueue = (int) (1/vehiclesPerSecondLeave);
			if (Time.getInstance().getCurrentTime() % leaveQueue == 0)
				if (!queue.isEmpty())
					queue.remove(0);
		}
	}
	
	public double getLength() {
		double length = 0;
		for (Vehicle vehicle : queue)
			length += vehicle.getLength();
		return length;
	}
	
	public int getSize() {
		return queue.size();
	}
	
	public void update(Observable obs0, Object obs1) {
		if (Time.getInstance().getCurrentTime() % trafficLightRate == 0)
			greenLight = !greenLight;
		enter();
		leave();
	}
}
